package com.cloudbroker.bcs.common.resource;

import com.cloudbroker.bcs.common.context.RuntimeContext;
import com.cloudbroker.bcs.common.util.IOUtil;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.InputStream;

/**
 * Created by xuyn15828 on 2016/5/24.
 */
public class DavResourceLoader extends DefaultResourceLoader {
    private static final Logger LOGGER = LoggerFactory.getLogger(DavResourceLoader.class);
    private Boolean enable_classpath;
    private static final String CLASSPATH_PREFIX = "classpath";

    @Override
    public Resource getResource(String location) {
        ApplicationContext ac = RuntimeContext.getSpringContext();
        if( ac instanceof ResourcePatternResolver ) {
            ResourcePatternResolver resolver = (ResourcePatternResolver) ac;
            try {
                Resource[] resources = resolver.getResources(location);
                if( null != resources && 0 != resources.length ) {
                    Resource resource = resources[0];
                    if( resource.exists() ) {
                        return resource;
                    }
                }
            }catch (Exception e) {
                LOGGER.error("get resource location error : " + location , e);
            }
            if( enable_classpath && !StringUtil.startWithIgnoreCase(location , CLASSPATH_PREFIX) ) {
                location = CLASSPATH_PREFIX + "*:" + location;
                return getResource(location);
            }
        }
        return super.getResource(location);
    }

    public boolean isEnable_classpath() {
        return enable_classpath;
    }

    public void setEnable_classpath(Boolean enable_classpath) {
        this.enable_classpath = ValueUtil.getBoolean(enable_classpath , true);
    }
}
